package com.yl.chainStore.services.impl.pay

import com.baomidou.mybatisplus.core.toolkit.Wrappers
import com.yl.chainStore.entity.pay.SysCompanyPayItem
import com.yl.chainStore.entity.pay.SysCompanyPayItemType
import com.yl.chainStore.mapper.pay.SysCompanyPayItemMapper
import com.yl.chainStore.mapper.pay.SysCompanyPayItemTypeMapper
import com.yl.chainStore.services.pay.ISysCompanyPayItemTypeService
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service

@Service
class SysCompanyPayItemTypeServiceImpl(
	private val sysCompanyPayItemTypeMapper: SysCompanyPayItemTypeMapper,
	private val sysCompanyPayItemMapper: SysCompanyPayItemMapper
): ISysCompanyPayItemTypeService {
	companion object {
		private val log = LoggerFactory.getLogger(ISysCompanyPayItemTypeService::class.java)
	}
	override fun update(type: SysCompanyPayItemType): ResponseBody {
		log.info("服务项目类型 ==> 修改项目类型 type:{}", type.toString())
		val byId = sysCompanyPayItemTypeMapper.selectById(type.id)?:return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if (type.superId != 0L) {
			val superType = sysCompanyPayItemTypeMapper.selectById(type.superId) ?: return returnError(
				ErrorCode.DATA_SAVE_FAILED,
				"找不到上级分类，请刷新重试"
			)
			if (superType.enabled == 0) {
				return returnError(
					ErrorCode.DATA_SAVE_FAILED,
					"上级类型已被删除"
				)
			}
			if(sysCompanyPayItemTypeMapper.haveSubType(superType.id,byId.id) != 0){
				return returnError(
					ErrorCode.DATA_SAVE_FAILED,
					"上级类型是本分类的子级"
				)
			}
		}
		byId.name  = type.name
		byId.superId = type.superId
		sysCompanyPayItemTypeMapper.updateById(byId)
		return returnSuccess()
	}

	override fun typeDetail(id: Long): SysCompanyPayItemType? {
		log.info("服务项目类型 ==> 服务项目类型详情 id:{}", id)
		val type = sysCompanyPayItemTypeMapper.selectById(id)
		if (type.enabled == 0) {
			return null
		}
		if (type.superId != 0L) {
			type.superType = sysCompanyPayItemTypeMapper.selectById(type.superId)
		}
		return sysCompanyPayItemTypeMapper.selectById(id)
	}

	override fun delType(id: Long): ResponseBody {
		log.info("收费项目类型管理 ==> 删除收费项目类型 id:{}", id)
		val type = sysCompanyPayItemTypeMapper.selectById(id) ?: return returnError(ErrorCode.DATA_IS_NOT_FIND)
		if(!type.canUpdate){
			return returnError(ErrorCode.DATA_CAN_NOT_DELETE,"不能删除的类型")
		}
		if (sysCompanyPayItemTypeMapper.selectCount(
				Wrappers.query<SysCompanyPayItemType>().eq("super_id", id).eq("enabled", 1)
			) != 0
		)
			return returnError(ErrorCode.DATA_DELETE_FAILED, "存在子级分类")

		if (sysCompanyPayItemMapper.selectCount(Wrappers.query<SysCompanyPayItem>().eq("type_id", id).eq("enabled", 1)) != 0)
			return returnError(ErrorCode.DATA_DELETE_FAILED, "该分类存在收费项目")

		type.enabled = 0
		sysCompanyPayItemTypeMapper.updateById(type)
		return returnSuccess()
	}
}
